package com.zhengbing.tj.common;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * MyBatis雪花算法主键生成拦截器
 *
 * @author zhengbing
 * @date 2025-07-07
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MybatisSnowflakeInterceptor implements Interceptor {
    private final Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];
        if (ms.getSqlCommandType() == org.apache.ibatis.mapping.SqlCommandType.INSERT && parameter != null) {
            MetaObject metaObject = SystemMetaObject.forObject(parameter);
            if (metaObject.hasGetter("id") && metaObject.getValue("id") == null) {
                metaObject.setValue("id", snowflake.nextId());
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {}
} 